<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${content.title} - 内容详情</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4cc9f0;
            --dark: #1d3557;
            --darker: #0d1b2a;
            --light: #f8f9fa;
            --gray: #8d99ae;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --card-bg: rgba(29, 53, 87, 0.8);
            --transition: all 0.3s ease;
        }

        body {
            background: linear-gradient(135deg, var(--darker) 0%, var(--dark) 100%);
            color: var(--light);
            min-height: 100vh;
            background-attachment: fixed;
            line-height: 1.6;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
        }

        .detail-container {
            max-width: 1400px;
            margin: 2rem auto;
            padding: 0 2rem;
        }

        .detail-header {
            background: var(--card-bg);
            border-radius: 15px;
            overflow: hidden;
            display: flex;
            gap: 2rem;
            margin-bottom: 3rem;
            padding: 2rem;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(10px);
        }

        .detail-poster {
            width: 300px;
            height: 450px;
            object-fit: cover;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            transition: var(--transition);
            opacity: 0;
            transform: translateY(10px);
        }

        .detail-poster.loaded {
            opacity: 1;
            transform: translateY(0);
        }

        .detail-poster.error {
            opacity: 1;
            transform: translateY(0);
            background: var(--dark);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .detail-info {
            flex: 1;
        }

        .detail-title {
            font-size: 2.2rem;
            margin-bottom: 0.5rem;
            color: var(--accent);
            font-weight: 700;
        }

        .detail-meta {
            color: var(--gray);
            margin-bottom: 1rem;
            font-size: 1.1rem;
        }

        .reply-form {
            margin-top: 1rem;
            padding: 1rem;
            background: rgba(13, 27, 42, 0.5);
            border-radius: 8px;
            display: none;
            animation: fadeIn 0.3s ease;
        }

        .reply-form.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .reply-input {
            width: 100%;
            padding: 0.8rem;
            border-radius: 4px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            background: rgba(255, 255, 255, 0.1);
            color: var(--light);
            margin-bottom: 0.5rem;
        }

        .reply-actions {
            display: flex;
            justify-content: flex-end;
            gap: 0.5rem;
        }

        .reply-btn {
            padding: 0.5rem 1rem;
            border-radius: 4px;
            font-size: 0.9rem;
        }

        .replies-container {
            margin-left: 2rem;
            margin-top: 1rem;
            border-left: 2px solid var(--primary);
            padding-left: 1rem;
        }

        .reply-card {
            background: rgba(13, 27, 42, 0.3);
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }

        .reply-header {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .reply-user {
            font-weight: 500;
            font-size: 0.9rem;
        }

        .reply-date {
            color: var(--gray);
            font-size: 0.8rem;
            margin-left: auto;
        }

        .reply-content {
            font-size: 0.9rem;
            line-height: 1.5;
        }

        .reply-action {
            color: var(--gray);
            font-size: 0.8rem;
            cursor: pointer;
            margin-top: 0.5rem;
            display: inline-block;
        }

        .reply-action:hover {
            color: var(--accent);
        }

        .detail-rating {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 1.5rem;
        }

        .detail-stars {
            color: var(--warning);
            display: flex;
            gap: 2px;
        }

        .detail-rating-value {
            font-weight: 600;
        }

        .detail-review-count {
            color: var(--gray);
            font-size: 0.9rem;
        }

        .btn {
            padding: 0.7rem 1.2rem;
            border-radius: 25px;
            font-weight: 500;
            font-size: 0.9rem;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            min-width: 120px;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
            border: none;
        }

        .btn-primary:hover {
            background: var(--secondary);
            transform: translateY(-2px);
        }

        .btn-outline {
            background: transparent;
            border: 2px solid var(--primary);
            color: var(--primary);
        }

        .btn-outline:hover {
            background: rgba(67, 97, 238, 0.1);
            transform: translateY(-2px);
        }

        .detail-section {
            background: var(--card-bg);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(5px);
        }

        .detail-section-title {
            font-size: 1.5rem;
            margin-bottom: 1rem;
            color: var(--accent);
            position: relative;
            padding-left: 1rem;
        }

        .detail-section-title::before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 4px;
            background: var(--accent);
            border-radius: 2px;
        }

        .detail-description {
            line-height: 1.8;
            margin-bottom: 1rem;
        }

        .reviews-container {
            margin-top: 2rem;
        }

        .review-card {
            background: rgba(13, 27, 42, 0.6);
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .review-header {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
        }

        .review-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 1rem;
            background: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }

        .review-user {
            font-weight: 500;
        }

        .review-date {
            color: var(--gray);
            font-size: 0.9rem;
            margin-left: auto;
        }

        .review-rating {
            color: var(--warning);
            margin-bottom: 0.5rem;
        }

        .review-content {
            line-height: 1.6;
        }

        .favorite-btn {
            background: var(--primary);
            color: white;
            padding: 0.7rem 1.2rem;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
            min-width: 120px;
        }

        .favorite-btn.active {
            background: var(--danger);
        }

        .favorite-btn:hover {
            transform: translateY(-3px);
        }

        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        @media (max-width: 992px) {
            .detail-header {
                flex-direction: column;
            }

            .detail-poster {
                width: 100%;
                height: auto;
                max-height: 500px;
            }

            .btn-container {
                flex-direction: column;
                gap: 1rem;
            }
        }

        @media (max-width: 768px) {
            .detail-container {
                padding: 0 1rem;
            }

            .detail-title {
                font-size: 1.8rem;
            }

            .detail-section {
                padding: 1rem;
            }

            .btn {
                padding: 0.6rem 1rem;
                font-size: 0.85rem;
            }
        }

        @media (max-width: 480px) {
            .btn {
                padding: 0.5rem 0.8rem;
                font-size: 0.8rem;
            }
        }

        .btn-container {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-top: 1.5rem;
        }
    </style>
</head>
<body>
<%@ include file="navbar.jsp" %>

<div class="detail-container">
    <div class="detail-header">
        <c:if test="${not empty content.imageUrl}">
            <img src="${content.imageUrl}" alt="${content.title}海报" class="detail-poster"
                 onerror="handleImageError(this)"
                 onload="handleImageLoad(this)">
        </c:if>
        <c:if test="${empty content.imageUrl}">
            <div class="detail-poster error">
                <i class="fas fa-image" style="font-size: 3rem; color: var(--gray);"></i>
            </div>
        </c:if>

        <div class="detail-info">
            <h1 class="detail-title">${content.title}</h1>

            <div class="detail-meta">
                <c:choose>
                    <c:when test="${content.type == 'movie'}">
                        导演: ${content.directorOrAuthor} | 上映: ${content.releaseOrPublishDate} | 类型: ${content.genre}
                    </c:when>
                    <c:when test="${content.type == 'book'}">
                        作者: ${content.directorOrAuthor} | 出版: ${content.releaseOrPublishDate} | 类型: ${content.genre}
                    </c:when>
                    <c:when test="${content.type == 'music'}">
                        艺术家: ${content.directorOrAuthor} | 发行: ${content.releaseOrPublishDate} | 流派: ${content.genre}
                    </c:when>
                </c:choose>
            </div>

            <div class="detail-rating">
                <div class="detail-stars">
                    <c:forEach begin="1" end="5" var="i">
                        <c:choose>
                            <c:when test="${i <= content.rating}">
                                <i class="fas fa-star"></i>
                            </c:when>
                            <c:when test="${i - 0.5 <= content.rating && content.rating < i}">
                                <i class="fas fa-star-half-alt"></i>
                            </c:when>
                            <c:otherwise>
                                <i class="far fa-star"></i>
                            </c:otherwise>
                        </c:choose>
                    </c:forEach>
                </div>
                <span class="detail-rating-value">${content.rating}</span>
                <span class="detail-review-count">${content.ratingCount} 条评价</span>
            </div>

            <div class="btn-container">
                <button class="favorite-btn ${isFavorite ? 'active' : ''}" data-content-id="${content.id}" data-content-type="${content.type}">
                    <i class="fas fa-heart"></i>
                    <span class="btn-text">${isFavorite ? '已收藏' : '收藏'}</span>
                </button>

                <button class="btn btn-primary" onclick="addReview(${content.id}, '${content.type}')">
                    <i class="fas fa-pen"></i>
                    <span class="btn-text">
                        <c:choose>
                            <c:when test="${content.type == 'movie'}">写影评</c:when>
                            <c:when test="${content.type == 'book'}">写书评</c:when>
                            <c:when test="${content.type == 'music'}">写乐评</c:when>
                            <c:otherwise>写评论</c:otherwise>
                        </c:choose>
                    </span>
                </button>

                <button class="btn btn-outline" onclick="shareContent()">
                    <i class="fas fa-share-alt"></i>
                    <span class="btn-text">分享</span>
                </button>
            </div>
        </div>
    </div>

    <div class="detail-section">
        <h2 class="detail-section-title">简介</h2>
        <p class="detail-description">${content.description}</p>

        <c:if test="${content.type == 'movie'}">
            <h2 class="detail-section-title">演职员</h2>
            <p>${content.castOrPublisher}</p>

            <h2 class="detail-section-title">时长</h2>
            <p>${content.durationOrPages}</p>
        </c:if>

        <c:if test="${content.type == 'book'}">
            <h2 class="detail-section-title">出版社</h2>
            <p>${content.castOrPublisher}</p>

            <h2 class="detail-section-title">页数</h2>
            <p>${content.durationOrPages}</p>
        </c:if>
    </div>

    <div class="detail-section">
        <h2 class="detail-section-title">用户评论</h2>

        <div class="reviews-container">
            <c:choose>
                <c:when test="${not empty reviews}">
                    <c:forEach items="${reviews}" var="review">
                        <div class="review-card">
                            <div class="review-header">
                                <div class="review-avatar">
                                    <i class="fas fa-user"></i>
                                </div>
                                <span class="review-user">${review.username}</span>
                                <span class="review-date">
                                    <fmt:formatDate value="${review.createTime}" pattern="yyyy-MM-dd HH:mm"/>
                                </span>
                            </div>

                            <div class="review-rating">
                                <c:forEach begin="1" end="5" var="i">
                                    <c:choose>
                                        <c:when test="${i <= review.rating}">
                                            <i class="fas fa-star"></i>
                                        </c:when>
                                        <c:otherwise>
                                            <i class="far fa-star"></i>
                                        </c:otherwise>
                                    </c:choose>
                                </c:forEach>
                            </div>

                            <div class="review-content">
                                    ${review.content}
                            </div>

                            <span class="reply-action" data-review-id="${review.id}">
                                <i class="fas fa-reply"></i> 回复
                            </span>

                            <div id="replyForm-${review.id}" class="reply-form">
                                <form class="reply-form-inner" data-review-id="${review.id}">
                                    <textarea name="content" class="reply-input" placeholder="写下你的回复..." required></textarea>
                                    <div class="reply-actions">
                                        <button type="button" class="btn btn-outline reply-btn cancel-reply">取消</button>
                                        <button type="submit" class="btn btn-primary reply-btn">提交回复</button>
                                    </div>
                                </form>
                            </div>

                            <c:if test="${not empty review.replies}">
                                <div class="replies-container">
                                    <c:forEach items="${review.replies}" var="reply">
                                        <div class="reply-card">
                                            <div class="reply-header">
                                                <span class="reply-user">${reply.username}</span>
                                                <span class="reply-date">
                                                    <fmt:formatDate value="${reply.createTime}" pattern="yyyy-MM-dd HH:mm"/>
                                                </span>
                                            </div>
                                            <div class="reply-content">
                                                    ${reply.content}
                                            </div>
                                        </div>
                                    </c:forEach>
                                </div>
                            </c:if>
                        </div>
                    </c:forEach>
                </c:when>
                <c:otherwise>
                    <p>暂无评论，快来发表第一条评论吧！</p>
                </c:otherwise>
            </c:choose>
        </div>
    </div>
</div>

<%@ include file="footer.jsp" %>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 图片加载处理
        function handleImageLoad(img) {
            img.classList.add('loaded');
        }

        function handleImageError(img) {
            img.classList.add('error');
            img.src = 'https://picsum.photos/300/450?random=' + Math.floor(Math.random() * 1000) + '&text=图片加载失败';
            img.alt = '图片加载失败';
            img.onload = null;
        }

        // 确保图片处理函数全局可用
        window.handleImageLoad = handleImageLoad;
        window.handleImageError = handleImageError;

        // 回复功能
        document.addEventListener('click', function(e) {
            if (e.target.closest('.reply-action')) {
                const replyAction = e.target.closest('.reply-action');
                const reviewId = replyAction.dataset.reviewId;
                const replyForm = document.getElementById(`replyForm-${reviewId}`);

                if (!replyForm) {
                    console.error(`未找到回复表单: ${reviewId}`);
                    return;
                }

                // 关闭其他打开的表单
                document.querySelectorAll('.reply-form.active').forEach(form => {
                    if (form.id !== `replyForm-${reviewId}`) {
                        form.classList.remove('active');
                        const otherId = form.id.replace('replyForm-', '');
                        const otherAction = document.querySelector(`.reply-action[data-review-id="${otherId}"]`);
                        if (otherAction) {
                            otherAction.innerHTML = '<i class="fas fa-reply"></i> 回复';
                        }
                    }
                });

                // 切换当前表单状态
                replyForm.classList.toggle('active');

                if (replyForm.classList.contains('active')) {
                    replyAction.innerHTML = '<i class="fas fa-times"></i> 取消回复';
                    setTimeout(() => {
                        const textarea = replyForm.querySelector('textarea');
                        if (textarea) textarea.focus();
                    }, 100);
                } else {
                    replyAction.innerHTML = '<i class="fas fa-reply"></i> 回复';
                }
            }

            // 取消回复
            if (e.target.classList.contains('cancel-reply')) {
                const form = e.target.closest('.reply-form');
                const reviewId = form.id.replace('replyForm-', '');
                form.classList.remove('active');
                const replyAction = document.querySelector(`.reply-action[data-review-id="${reviewId}"]`);
                if (replyAction) {
                    replyAction.innerHTML = '<i class="fas fa-reply"></i> 回复';
                }
            }
        });

        // 提交回复
        document.addEventListener('submit', function(e) {
            if (e.target.closest('.reply-form-inner')) {
                e.preventDefault();
                const form = e.target.closest('.reply-form-inner');
                const reviewId = form.dataset.reviewId;
                const content = form.querySelector('textarea').value.trim();

                if (!content) {
                    alert('回复内容不能为空');
                    form.querySelector('textarea').style.borderColor = 'var(--danger)';
                    form.querySelector('textarea').focus();
                    return;
                }

                const submitBtn = form.querySelector('button[type="submit"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
                submitBtn.disabled = true;

                fetch('${pageContext.request.contextPath}/add-reply', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        reviewId: reviewId,
                        content: content
                    })
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应异常: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            const newReply = createReplyElement(data.reply);
                            let repliesContainer = form.closest('.review-card').querySelector('.replies-container');
                            if (!repliesContainer) {
                                repliesContainer = document.createElement('div');
                                repliesContainer.className = 'replies-container';
                                form.closest('.review-card').appendChild(repliesContainer);
                            }
                            repliesContainer.insertAdjacentHTML('afterbegin', newReply);
                            form.reset();
                            form.closest('.reply-form').classList.remove('active');
                            const replyAction = document.querySelector(`.reply-action[data-review-id="${reviewId}"]`);
                            if (replyAction) {
                                replyAction.innerHTML = '<i class="fas fa-reply"></i> 回复';
                            }
                        } else {
                            alert(data.message || '回复失败，请重试');
                        }
                    })
                    .catch(error => {
                        console.error('回复错误:', error);
                        alert('回复过程中发生错误: ' + error.message);
                    })
                    .finally(() => {
                        submitBtn.innerHTML = '提交回复';
                        submitBtn.disabled = false;
                    });
            }
        });

        // 收藏功能
        document.querySelectorAll('.favorite-btn').forEach(button => {
            button.addEventListener('click', function() {
                const contentId = this.dataset.contentId;
                const contentType = this.dataset.contentType;
                const isFavorite = this.classList.contains('active');
                const originalHTML = this.innerHTML;

                this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
                this.disabled = true;

                fetch('${pageContext.request.contextPath}/favorite', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: isFavorite ? 'remove' : 'add',
                        contentId: contentId,
                        contentType: contentType
                    })
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应异常: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(data => {
                        this.innerHTML = originalHTML;
                        this.disabled = false;
                        if (data.success) {
                            this.classList.toggle('active');
                            this.querySelector('.btn-text').textContent = this.classList.contains('active') ? '已收藏' : '收藏';
                        } else {
                            console.error('收藏操作失败:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('收藏请求错误:', error);
                        this.innerHTML = originalHTML;
                        this.disabled = false;
                    });
            });
        });

        // 初始化收藏按钮状态
        document.querySelectorAll('.favorite-btn').forEach(btn => {
            const icon = btn.querySelector('i');
            const text = btn.querySelector('.btn-text');
            if (btn.classList.contains('active')) {
                icon.className = 'fas fa-heart';
                text.textContent = '已收藏';
            } else {
                icon.className = 'far fa-heart';
                text.textContent = '收藏';
            }
        });
    });

    // 创建回复元素
    function createReplyElement(reply) {
        if (!reply || !reply.username || !reply.content || !reply.createTime) {
            return '<div class="reply-card">回复加载失败</div>';
        }

        let formattedDate;
        try {
            const date = new Date(reply.createTime);
            formattedDate = date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (e) {
            formattedDate = '未知时间';
        }

        return `
        <div class="reply-card">
            <div class="reply-header">
                <span class="reply-user">${reply.username}</span>
                <span class="reply-date">${formattedDate}</span>
            </div>
            <div class="reply-content">${reply.content}</div>
        </div>
    `;
    }

    // 添加评论
    function addReview(contentId, contentType) {
        const isLoggedIn = ${not empty sessionScope.user};
        if (!isLoggedIn) {
            alert('请先登录后再发表评论');
            window.location.href = '${pageContext.request.contextPath}/Userlogin.jsp?redirect=' +
                encodeURIComponent(window.location.pathname + window.location.search);
            return;
        }

        if (!contentId || !contentType) {
            console.error('无效的内容参数:', {contentId, contentType});
            alert('无法获取内容信息，请刷新页面重试');
            return;
        }

        window.location.href = '${pageContext.request.contextPath}/add-review.jsp?contentId=' + contentId + '&type=' + contentType;
    }

    // 分享功能
    function shareContent() {
        const shareUrl = window.location.href;
        const shareTitle = '${content.title} - 内容评级平台';

        if (navigator.share) {
            navigator.share({
                title: shareTitle,
                url: shareUrl
            })
                .catch(error => console.log('分享失败:', error));
        } else {
            prompt('复制以下链接分享给朋友:', shareUrl);
        }
    }
</script>
</body>
</html>